<?php
/**
 * Viewer ini menerima data dalam sebuah array 'data', yang minimal berisi:
 * ['metadata']
 *		['n_fields']	= banyaknya field pada tabel
 *		['fields']		= array berisi informasi field-field tabel
 *			['name']		= nama field pada tabel
 *			['alias']		= displayed name dari field
 *			['type']		= tipe field tabel (converted)
 *			['values']	= list of possible values, only for ENUM
 *			['nullable']	= if true: cannot enter null as value
 *			['editable']	= if false: read only
 *			['viewable']	= if false: hidden
 *		['fields_list']	= array berisi daftar field-field tabel	 
 *		['fields_aliases']
 *						= array berisi mapping alias field-field tabel
 *		['keys']		= array berisi keys dari tabel 
 *			['n_tables']	 = no of table involved
 *			['pri_table']	 = name of primary table
 *			['primary']	=> Primary Keys
 *				[table]					of table 'table'
 *				['name']  = key name, usually PRIMARY
 *				['value'] = single value or array if composite 
 *
 * ['data']
 *			['n_records'] 		= banyaknya record hasil query
 *			['n_all_records']	= banyaknya record pada table
 *			['records']			= array berisi records hasil query
 */
 
//---------- EKSTRAK $data menjadi $metadata dan $data
extract($data);

//---------- GET SETTINGS FROM CONFIG FILE
include "_get_settings.php";

//---------- BUILD HEADER TABLE
// $table_fields: daftar fields yang viewable
// $table_fileds_idx: index dari $table_fileds pada $metadata['fields'];
$table_fields = array();
$table_fields_idx = array();
foreach ($metadata['fields'] as $idx => $val) {
	$table_field_idx = $idx;
	$table_field = $val['name'];

	if ($val['viewable']) {
		$table_fields[] = $table_field;
		$table_fields_idx[] = $table_field_idx;
	}
}

//print_r_pre($table_fields);

// $table_header['fields'] = $table_fields, tetapi nama field diubah menjadi aliasnya, jika didefinisikan
// $table_header['filters'] = input box untuk filtering
$table_header = array();
$table_filters = array();
foreach($table_fields as $idx => $value) {
	if (isset($options['order_by']['field']) && (strcasecmp($options['order_by']['field'], $value)==0)) { 
		if (strcasecmp($options['order_by']['type'], 'ASC')==0) {
			$type = 'DESC';
			$indicator = '<sup><small>'.anchor(get_function_from_uri($this->uri->uri_string()).'/'.$this->common->create_uri_from_options(array_merge($options, array('order_by' => NULL))), '+').'</small></sup>';
		} else {
			$type = 'ASC';
			$indicator = '<sup><small>'.anchor(get_function_from_uri($this->uri->uri_string()).'/'.$this->common->create_uri_from_options(array_merge($options, array('order_by' => NULL))), '&ndash;').'</small></sup>';
		}
	} else {
		$type = 'ASC';
		$indicator = '';
	}
	$table_header['fields'][$idx] = anchor(get_function_from_uri($this->uri->uri_string()).'/'.$this->common->create_uri_from_options(array_merge($options, array('order_by' => array('field' => $value, 'type' => $type)))), $metadata['fields_aliases'][$value]).$indicator.'<div class="field_name">'.$value.'</div>';

	$filter_control = get_function_from_uri($this->uri->uri_string()).'/'.$this->common->create_uri_from_options(array_merge($options, array('filter' => NULL)));
	$table_header['filters'][$idx] = form_input($value, $options['filter'][$value], 'style="width: 100%;" onkeypress="{if (event.keyCode==13) filter(this.form, \''.site_url($filter_control).'\')}"');
}

//print_r_pre($table_header);

//---------- BUILD ISI TABLE
$table_content = array();
foreach ($data['records'] as $ridx => $rval) {
	foreach ($table_fields as $col) {
		$table_content[$ridx][] = $rval[$col];
	}
}

//print_r_pre($table_content);

//---------- BUILD FOOTER TABLE
$table_footer = array();

//---------- TAMBAHKAN ACTIONS
// modify header
// -- left-right actions
foreach (array('left', 'right') as $pos) {
	$curr_header = $pos.'_header';
	${$curr_header} = array();
	if (isset($actions[$pos])) {
		reset($actions[$pos]);
		$curr = current($actions[$pos]);
		if (is_array($curr)) {
			foreach ($curr as $aidx => $aval) {
				${$curr_header}[] = '';
			}
		}
	}
}

if (isset($actions['bulk']['processor'])) {
	$bulk_select = array(form_open($actions['bulk']['processor']));
} else {
	$bulk_select = array();
}

$table_header['fields'] = array_merge($bulk_select, $left_header, $table_header['fields'], $right_header);
for ($i=0; $i<count($bulk_select)+count($left_header); $i++) {
	array_unshift($table_header['filters'], "");
}
for ($i=0; $i<count($right_header); $i++) {
	array_push($table_header['filters'], "");
}

//print_r_pre($data);

// modify content
foreach ($table_content as $ridx => $rval) {
	foreach ($rval as $cidx => $cval) {
		$type = $metadata['fields'][$table_fields_idx[$cidx]]['type'];
		
		// in_place actions
		if (isset($actions['in_place'][$ridx][$cidx]) && (!is_empty($actions['in_place'][$ridx][$cidx])) && (!is_null_or_false($actions['in_place'][$ridx][$cidx])))
			$table_content[$ridx][$cidx] = str_from_template($actions['in_place'][$ridx][$cidx], array('VALUE' => $table_content[$ridx][$cidx]));
		
		// jika tipe == FILE atau tipe == IMAGE, tambahkan aksi untuk download
		if ((strcasecmp($type, 'FILE')==0) || (strcasecmp($type, 'IMAGE')==0)) {
			$filename = $metadata['fields'][$table_fields_idx[$cidx]]['properties']['filename'];		
			$filename = str_from_template($filename, $data['records'][$ridx]);
			$this->common->create_download_button($filename, $table_content[$ridx][$cidx]);
		}
		// jika tipe == PASSWORD, mask the data
		if (strcasecmp($type, 'PASSWORD')==0) {
			$this->common->mask_password($table_content[$ridx][$cidx]);
		}
	}
}

// -- left-right actions
$new_table_content = array();

foreach ($table_content as $ridx => $rval) {
	foreach (array('left', 'right') as $pos) {
		if (is_array($actions[$pos][$ridx])) {
			foreach ($actions[$pos][$ridx] as $aidx => $aval) {
				$record = $this->common->create_uri_record_part($data['records'][$ridx]);
				$actions[$pos][$ridx][$aidx] = str_from_template($aval, array_merge(array('RECORD' => $record), $label_template));
			}
		}
	}
	
	if (isset($actions['bulk']) && (isset($actions['bulk']['list'])) && (!is_empty($actions['bulk']['list']))) {
		$bulk_select = array('<input type="checkbox" name="id[]" value="'.$data['records'][$ridx]['id'].'"  />'); //XXX: assuming every record follows our convention: has id field
	} else {
		$bulk_select = array();
	}
	
	if (!is_array($actions['left'][$ridx])) {
		$actions['left'][$ridx] = array();
	}
	
	if (!is_array($actions['right'][$ridx])) {
		$actions['right'][$ridx] = array();
	}
	
	$new_table_content[$ridx] = array_merge($bulk_select, $actions['left'][$ridx], $table_content[$ridx], $actions['right'][$ridx]);
}
$table_content = $new_table_content;

// modify footer

if (isset($actions['bulk']) && (isset($actions['bulk']['list'])) && (!is_empty($actions['bulk']['list']))) {
	$str_bulk_actions = '';
	foreach($actions['bulk']['list'] as $aidx => $aval) {
		$str_bulk_actions .= $aval._MED_SEP;
	}
	$table_footer[] = '<td></td><td colspan="0">'.$str_bulk_actions.form_close().'</td>';
}
				
$table_footer_str  = '<td align="center" colspan="0">';

$page = $this->common->create_uri_page_part($options['page']);
$first_page = $this->common->create_uri_from_options(array_merge($options, array('page' => 1)));
if ($options['page']-1>=1) {
	$prev_page = $this->common->create_uri_from_options(array_merge($options, array('page' => $options['page']-1)));
} else {
	$prev_page = $this->common->create_uri_from_options(array_merge($options, array('page' => $options['n_page'])));
}
if ($options['page']+1<=$options['n_page']) {
	$next_page = $this->common->create_uri_from_options(array_merge($options, array('page' => $options['page']+1)));
} else {
	$next_page = $this->common->create_uri_from_options(array_merge($options, array('page' => 1)));
}
$last_page = $this->common->create_uri_from_options(array_merge($options, array('page' => $options['n_page'])));

$arr_template = array_merge(array('CURR_PAGE' => $options['page'], 'N_PAGE' => $options['n_page'], 'FIRST_PAGE' => $first_page, 'PREV_PAGE' => $prev_page, 'NEXT_PAGE' => $next_page, 'LAST_PAGE' => $last_page), $label_template);

if (is_array($actions['nav']['left'])) {
	foreach ($actions['nav']['left'] as $aidx => $aval) {	
		$table_footer_str .= str_from_template($aval, $arr_template)._WIDE_SEP;
	}
}

if (is_array($actions['nav']['center'])) {
	foreach ($actions['nav']['center'] as $aidx => $aval) {	
		$table_footer_str .= str_from_template($aval, $arr_template);
	}
}

if (is_array($actions['nav']['right'])) {
	foreach ($actions['nav']['right'] as $aidx => $aval) {	
		$table_footer_str .= _WIDE_SEP.str_from_template($aval, $arr_template);
	}
}
$table_footer_str  .= '</td>';

$table_footer[] = $table_footer_str;

//---------- DISPLAY SEARCH FORM
//$this->load->view('form/search');

//---------- DISPLAY TABLE
$table_data = compact('table_header', 'table_content', 'table_footer', 'label', 'table_records_per_page');
$this->load->view('viewer/tabular_table', $table_data);

//---------- DISPLAY IMPORT/EXPORT UTILS
$this->load->view('nav/tabular_export_import');

/* EOF views/viewer/tabular.php */